
//
//  YAYIScanViewController.m
//  yayi
//
//  Created by Veer on 16/6/16.
//  Copyright © 2016年 Veer. All rights reserved.
//

#import "XScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "UIImage+VR.h"


@interface XScanViewController () <AVCaptureMetadataOutputObjectsDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    int num;
    BOOL upOrdown;
    NSTimer * timer;
}

@property (nonatomic,strong)UIButton *backBtn;

@property (nonatomic, strong) AVCaptureDevice * device;
@property (nonatomic, strong) AVCaptureDeviceInput * input;
@property (nonatomic, strong) AVCaptureMetadataOutput * output;
@property (nonatomic, strong) AVCaptureSession * session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer * preview;

@property (nonatomic, retain) UIImageView *lineView;
@property (nonatomic, retain) UIImageView *scanView;;


@end

@implementation XScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.view.backgroundColor = [UIColor grayColor];
    self.title = @"条码扫描";

    
    [self setupSubview];
    [self setupCamera];
    
    [self setupNav];
}



-(void)setupNav
{
    
    UIView *navBarView = [[UIView alloc] init];
    [self.view addSubview:navBarView];
    [navBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(STATUS_BAR_HEIGHT);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT);
    }];
    
    // 保存
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"back_white"] forState:UIControlStateNormal];
    //    backBtn.imageEdgeInsets = UIEdgeInsetsMake(2, 0, 2, 0);
    [navBarView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.centerY.mas_equalTo(navBarView);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
    
    // 标题
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"扫一扫";
    titleLbl.font = VRFont(16);
    titleLbl.textColor = [UIColor whiteColor];
    titleLbl.textAlignment = NSTextAlignmentCenter;
    [navBarView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(navBarView);
    }];
    
    // 右边按钮
    UIButton *albumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [albumBtn setTitle:@"相册" forState:UIControlStateNormal];
    albumBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [albumBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    albumBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [albumBtn addTarget:self action:@selector(onAlbumBtnClick:) forControlEvents:UIControlEventTouchUpInside];
//    albumBtn.frame = CGRectMake(0, 0, 70, 24);
    [navBarView addSubview:albumBtn];
    [albumBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-10);
        make.centerY.mas_equalTo(navBarView);
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(44);
    }];
}


- (void)setupSubview
{
    upOrdown = NO;
    num = 0;
    
    // 扫码框图片
    CGFloat scanWH = kScreenWidth * 0.64;
    CGFloat scanX = (kScreenWidth - scanWH) / 2;
    CGFloat scanY = 160;
    
    UIImageView *scanView = [[UIImageView alloc] init];
    scanView.image = [UIImage resizedImageWithName:@"scanscanBg"];
    scanView.backgroundColor = [UIColor clearColor];
    scanView.frame = CGRectMake(scanX, scanY, scanWH, scanWH);
    [self.view addSubview:scanView];
    self.scanView = scanView;
    
    
    UIImage *img = [[UIImage imageNamed:@"scanLine"] stretchableImageWithLeftCapWidth:110 topCapHeight:1.5];
    _lineView = [[UIImageView alloc] initWithImage:img];
    _lineView.frame = CGRectMake(scanView.x , scanView.y, scanView.width, 2);
    [self.view addSubview:_lineView];
    
    
    // 添加模糊背景
    [self creatMaskView:CGRectMake(0, 0, kScreenWidth, self.scanView.y)];
    [self creatMaskView:CGRectMake(0, self.scanView.y, self.scanView.x, self.scanView.height)];
    [self creatMaskView:CGRectMake(kScreenWidth - self.scanView.x, self.scanView.y, self.scanView.x, self.scanView.height)];
    [self creatMaskView:CGRectMake(0, CGRectGetMaxY(self.scanView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.scanView.frame))];
    
    
    UILabel *labIntroudction= [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(scanView.frame) + 15, kScreenWidth, 30)];
    labIntroudction.backgroundColor = [UIColor clearColor];
    labIntroudction.textAlignment = NSTextAlignmentCenter;
    labIntroudction.numberOfLines = 0;
    labIntroudction.textColor = [UIColor whiteColor];
    labIntroudction.font = [UIFont systemFontOfSize:13];
    labIntroudction.text = @"请将二维码/条形码放入框内，既可自动扫描";
    [self.view addSubview:labIntroudction];
    
//    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    [self loopDrawLine];
}


/**
 *  添加模糊效果
 */
- (void)creatMaskView:(CGRect)rect {
    UIView *view = [[UIView alloc] initWithFrame:rect];
    view.backgroundColor = [UIColor blackColor];
    view.alpha = 0.5;
    [self.view addSubview:view];
}


- (void)setupCamera
{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    NSError *error = nil;
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    if (error) {
        NSString* errMsg;
        if (error.code == -11852) {
            errMsg = @"请在设置中打开相机权限";
        }else{
            errMsg = [error.userInfo objectForKey:NSLocalizedDescriptionKey];
        }
        
        [[[UIAlertView alloc] initWithTitle:@"提示" message:errMsg delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil] show];
        return;
    }
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc] init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //    output.rectOfInterest = [self turnRect:_scanZomeBack.frame];
    CGFloat outputX = (self.scanView.y) / kScreenHeight;
    CGFloat outputY = self.scanView.x / kScreenWidth;
    CGFloat outputW = self.scanView.height / kScreenHeight;
    CGFloat outputH = self.scanView.width / kScreenWidth;
    _output.rectOfInterest = CGRectMake(outputX, outputY, outputW, outputH);
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode,
                                   AVMetadataObjectTypeUPCECode,
                                   AVMetadataObjectTypeCode39Code,
                                   AVMetadataObjectTypeCode39Mod43Code,
                                   AVMetadataObjectTypeEAN13Code,
                                   AVMetadataObjectTypeEAN8Code,
                                   AVMetadataObjectTypeCode93Code,
                                   AVMetadataObjectTypeCode128Code,
                                   AVMetadataObjectTypePDF417Code,
                                   AVMetadataObjectTypeQRCode,
                                   AVMetadataObjectTypeAztecCode];
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame = self.view.bounds;//CGRectMake(25 * YAYIScreenScale, 35 * YAYIScreenScale,self.view.frame.size.width - 50 * YAYIScreenScale,290);
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    // Start
    [_session startRunning];
    
    
}


#pragma mark 两种动画方式
-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        self.lineView.frame = CGRectMake(self.scanView.x, self.scanView.y + 2 * num, self.scanView.width, 2);
        if (2 * num >= self.scanView.height) {
            upOrdown = YES;
        }
    }else {
        num --;
        self.lineView.frame = CGRectMake(self.scanView.x, self.scanView.y + 2 * num, self.scanView.width, 2);
        if (num <= 0) {
            upOrdown = NO;
        }
    }
}


- (void)loopDrawLine {
    
    CGFloat x = CGRectGetMinX(_scanView.frame);
    CGFloat y = CGRectGetMinY(_scanView.frame);
    CGFloat w = CGRectGetWidth(_scanView.frame);
    CGFloat h = CGRectGetHeight(_scanView.frame);
    
    CGRect start = CGRectMake(x, y, w, 2);
    CGRect end = CGRectMake(x, y + h - 2, w, 2);
    self.lineView.frame = start;
    
    __weak typeof(self) weakself = self;
    [UIView animateWithDuration:2 animations:^{
        _lineView.frame = end;
    } completion:^(BOOL finished) {
        [weakself loopDrawLine];
    }];
}


#pragma mark - 响应事件
-(void)backAction:(UIButton *)sender
{
    [timer invalidate];
    
    if (self.navigationController.childViewControllers.count > 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self dismissViewControllerAnimated:NO completion:nil];
    }
}

- (void)onAlbumBtnClick:(UIButton *)sender
{
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    [picker.navigationBar setBackgroundImage:[UIImage imageWithColor:MAINColor] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
    [self presentViewController:picker animated:true completion:nil];
}


#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    NSString *stringValue;
    
    if (metadataObjects != nil && [metadataObjects count] >0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
    }
    
    [_session stopRunning];
    [timer invalidate];
    
    [self dismissViewControllerAnimated:NO completion:nil];
    
    if ([self.delegate respondsToSelector:@selector(getScanResultxxxxxxxxxxx:)]) {
        [self.delegate getScanResultxxxxxxxxxxx:stringValue];
    }
}


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:true completion:^{
        
        UIImage *image = info[UIImagePickerControllerEditedImage];
        if (!image) {
            image = info[UIImagePickerControllerOriginalImage];
        }
        
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        
        // kCIContextUseSoftwareRenderer : 软件渲染 -- 可以消除 "BSXPCMessage received error for message: Connection interrupted" 警告
        // kCIContextPriorityRequestLow : 低优先级在 GPU 渲染-- 设置为false可以加快图片处理速度
        CIContext *context = [CIContext contextWithOptions:@{kCIContextUseSoftwareRenderer : @(true), kCIContextPriorityRequestLow : @(false)}];
        
        CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:nil];
        CIImage *ciImage = [CIImage imageWithData:imageData];
        
        NSArray *ar = [detector featuresInImage:ciImage];
        CIQRCodeFeature *feature = [ar firstObject];
        NSLog(@"detector: %@", detector);
        NSLog(@"context: %@", feature.messageString);
        
        if (feature.messageString.length > 0) {
            
            // 关闭session
            [_session stopRunning];
            [timer invalidate];
            
            [self dismissViewControllerAnimated:NO completion:nil];
            
            if ([self.delegate respondsToSelector:@selector(getScanResultxxxxxxxxxxx:)]) {
                [self.delegate getScanResultxxxxxxxxxxx:feature.messageString];
            }
        }else{
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"未发现二维码，请重试" preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
            [self presentViewController:alert animated:true completion:nil];
        }
    }];
}


- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        
        if (self.isViewLoaded && !self.view.window) {
            
            self.view = nil;
        }
    }
}

@end
